/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iss.examsys.ejb;

import com.iss.examsys.entity.Role;
import com.iss.examsys.entity.User;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author User
 */
@Stateless
public class UserBean {

    @PersistenceContext EntityManager em;

    public void create(User user){
        user.setPassword(sha256(user.getPassword()));
        em.persist(user);
    }
    
    public void edit(User user) {
        user.setPassword(sha256(user.getPassword()));
        em.merge(user);
    }
    
    public void remove(User user) {
        em.remove(em.merge(user));
    }
    
    public User findById(long id){        
        User entity = em.find(User.class, id);        
        return entity;
    }
           
    public List<User> findUsersByRoles(String role){
        TypedQuery<Role> result = em.createNamedQuery("Role.findByGroupName", Role.class);
        result.setParameter("groupName", role);
           
        List<Role> roleList = result.getResultList();
           
        List<User> userList = new ArrayList<User>();
           
        for(Iterator iter = roleList.iterator();iter.hasNext();){
            Role userRole = (Role) iter.next();
            userList.add(userRole.getUser());
        }
           
        return userList;
    }
    
    public User findByUserId(String userId){        
        TypedQuery<User> result = em.createNamedQuery("User.findByUserId", User.class);
        result.setParameter("userId", userId);
        
        User user = null;
        
        if(result.getResultList().size()>0){
            user = result.getResultList().get(0);
        }
    
        return user;
    }
    
    public User findByUserEmail(String userEmail){        
        TypedQuery<User> result = em.createNamedQuery("User.findByEmail", User.class);
        result.setParameter("email", userEmail);
        
        User user = null;
        
        if(result.getResultList().size()>0){
            user = result.getResultList().get(0);
        }
    
        return user;
    }
    
    public String getAccessAuthentication(){
        ExternalContext ctx = FacesContext.getCurrentInstance()
                .getExternalContext();
        String userId = ctx.getUserPrincipal().getName();
        User user = findByUserId(userId);
        ArrayList<Role> roles = new ArrayList<Role>(user.getRoleCollection());
        
        Role userRole = roles.get(0);
        
        String authenticatedRole = userRole.userGroup().getGroupName();

        switch (authenticatedRole){
            case "admins": return "/faces/menu/admin/menu.xhtml";
            case "lecturers": return "/faces/menu/lecturer/menu.xhtml";
            case "students": return "/faces/examsession/examList.xhtml";
            default: return "";
         }
    }
    
    private static String sha256(String base) {
            try{
                MessageDigest digest = MessageDigest.getInstance("SHA-256");
                byte[] hash = digest.digest(base.getBytes("UTF-8"));
                StringBuilder hexString = new StringBuilder();

                for (int i = 0; i < hash.length; i++) {
                    String hex = Integer.toHexString(0xff & hash[i]);
                    if(hex.length() == 1) hexString.append('0');
                    hexString.append(hex);
                }

                return hexString.toString();
            } catch(NoSuchAlgorithmException | UnsupportedEncodingException ex){
                throw new RuntimeException(ex);
            }
    }
}
